package com.myz.rabbitmq.study8;

import com.myz.rabbitmq.utils.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Consumer01 {
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    public static final String DEAD_EXCHANGE = "dead_exchange";

    // 普通队列名称
    public static final String NORMAL_QUEUE = "normal_queue";
    public static final String DEAD_QUEUE = "dead_queue";
    // 死信名称

    public static void main(String[] args) throws Exception {
        // 1.获取信道
        Channel channel = RabbitMqUtils.getChannel();
        // 2.声明交换机 declare exchange
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        // 3.声明队列 declare queue
        // 普通队列
        Map<String,Object> arguments = new HashMap<>();
        // 设置信息过期时间 需要注意的是一共有两个地方可以设置信息过期时间，生产者发送消息时也可以设置过期时间，一般在生产者那里设置消息过期时间
//        arguments.put("x-message-ttl",10000);
        // 正常队列设置死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        // 设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key","lisi");
        // 设置正常队列最大长度，消息超过最大长度则成为死亡信息
//        arguments.put("x-max-length",6);
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments); // queueName,持久化,共享,自动删除,其它

        // 死信队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null); // queueName,持久化,共享,自动删除,其它

        // 绑定普通的交换机与队列 绑定死信的交换机与死信队列
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");

        DeliverCallback deliverCallback = (consumeTag,message) -> {
            String msg = new String(message.getBody(),StandardCharsets.UTF_8);
            if (msg.equals("5-message")) {
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);  // false不放回原队列
            }else {
                System.out.println("Consumer01 receive a message:"+new String(message.getBody(), StandardCharsets.UTF_8));
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false); // false表示不是批量确认
            }
        };
        // 4.绑定队列
        System.out.println("ReceiveLogsTopic01 waiting receive message...");
        // 5.接收消息 开启手动应答
        channel.basicConsume(NORMAL_QUEUE,true,deliverCallback, (CancelCallback) null);
    }
}
